<template>
  <div>
    <div v-permission="['settle:pre-sheet:query']">
      <page-wrapper content-full-height fixed-height>
        <!-- 数据列表 -->
        <vxe-grid
          id="SettlePreSheet"
          ref="grid"
          resizable
          show-overflow
          highlight-hover-row
          keep-source
          row-id="id"
          :columns="tableColumn"
          :toolbar-config="toolbarConfig"
          :custom-config="{}"
          :pager-config="{}"
          :loading="loading"
          height="auto"
        >
          <template #form>
            <j-border>
              <j-form :span="6">
                <!-- 商品名称和编号的容器 -->
                <!-- <div class="product-search-container"> -->
                <j-form-item label="商品名称" class="full-width">
                  <a-input
                    v-model:value="searchFormData.code"
                    allow-clear
                    placeholder="请输入商品名称"
                  />
                </j-form-item>
                <j-form-item label="商品编号" class="full-width">
                  <supplier-selector
                    v-model:value="searchFormData.supplierId"
                    placeholder="请选择商品编号"
                  />
                </j-form-item>
                <!-- 查询按钮 -->
                <!-- <a-button type="primary" :icon="h(SearchOutlined)" @click="search" class="search-btn">
                    查询
                  </a-button> -->
                <!-- </div> -->

                <j-form-item label="生产单号">
                  <a-input
                    v-model:value="searchFormData.code"
                    placeholder="请输入生产单号"
                    allow-clear
                  />
                </j-form-item>
                <j-form-item label="计量单位">
                  <a-input
                    v-model:value="searchFormData.code"
                    placeholder="请输入计量单位"
                    allow-clear
                  />
                </j-form-item>
                <j-form-item label="多属性">
                  <a-input
                    v-model:value="searchFormData.code"
                    placeholder="请输入多属性"
                    allow-clear
                  />
                </j-form-item>
                <j-form-item label="订购数量">
                  <a-input
                    v-model:value="searchFormData.code"
                    placeholder="请输入订购数量"
                    required
                    allow-clear
                  />
                </j-form-item>
                <j-form-item label="生产数量">
                  <a-input
                    v-model:value="searchFormData.code"
                    placeholder="请输入生产数量"
                    allow-clear
                  />
                </j-form-item>
                <j-form-item label="总需求量">
                  <a-input
                    v-model:value="searchFormData.code"
                    placeholder="请输入总需求量"
                    allow-clear
                  />
                </j-form-item>
                <j-form-item label="销售订单号">
                  <a-input
                    v-model:value="searchFormData.code"
                    placeholder="请输入销售订单号"
                    allow-clear
                  />
                </j-form-item>
                <j-form-item label="客户原始单号">
                  <a-input
                    v-model:value="searchFormData.code"
                    placeholder="请输入客户原始单号"
                    allow-clear
                  />
                </j-form-item>
                <j-form-item label="计划完工" required class="timeData">
                  <!-- <div class="date-range-container"> -->
                  <a-space>
                    <a-date-picker
                      v-model:value="searchFormData.createStartTime"
                      placeholder="请选择计划完工"
                      value-format="YYYY-MM-DD 00:00:00"
                      class="full-width"
                    />
                  </a-space>
                </j-form-item>
                <j-form-item label="单据备注">
                  <a-textarea
                    v-model:value="searchFormData.code"
                    allow-clear
                    auto-size
                    placeholder="请输入备注"
                  />
                </j-form-item>
              </j-form>
            </j-border>
            <!-- 将菜单移到这里，form template的最后 -->
            <a-menu v-model:selectedKeys="selectedKeys" mode="horizontal" class="custom-menu">
              <a-menu-item key="required">所需物料</a-menu-item>
              <a-menu-item key="production">生产物料</a-menu-item>
            </a-menu>
          </template>
          <!-- 工具栏 -->
          <template #toolbar_buttons>
            <a-space>
              <a-button type="primary" :icon="h(SearchOutlined)" @click="search">查询</a-button>
              <a-button
                v-permission="['settle:pre-sheet:add']"
                type="primary"
                :icon="h(PlusOutlined)"
                @click="$router.push('/settle/supplier/pre-sheet/add')"
                >新增</a-button
              >
              <a-button
                v-permission="['settle:pre-sheet:approve']"
                :icon="h(CheckOutlined)"
                @click="batchApprovePass"
                >审核通过</a-button
              >
              <a-button
                v-permission="['settle:pre-sheet:approve']"
                :icon="h(CloseOutlined)"
                @click="batchApproveRefuse"
                >审核拒绝</a-button
              >
              <a-button
                v-permission="['settle:pre-sheet:delete']"
                danger
                :icon="h(DeleteOutlined)"
                @click="batchDelete"
                >批量删除</a-button
              >
              <a-button
                v-permission="['settle:pre-sheet:export']"
                :icon="h(DownloadOutlined)"
                @click="exportList"
                >导出</a-button
              >
            </a-space>
          </template>

          <!-- 操作 列自定义内容 -->
          <template #action_default="{ row }">
            <table-action outside :actions="createActions(row)" />
          </template>
        </vxe-grid>
      </page-wrapper>

      <!-- 查看窗口 -->
      <!-- <detail :id="id" ref="viewDialog" /> -->

      <approve-refuse ref="approveRefuseDialog" @confirm="doApproveRefuse" />
    </div>
  </div>
</template>

<script>
import { h, defineComponent } from 'vue';
// import Detail from './detail.vue';
import ApproveRefuse from '@/components/ApproveRefuse';
import moment from 'moment';
import {
  SearchOutlined,
  PlusOutlined,
  CheckOutlined,
  CloseOutlined,
  DeleteOutlined,
  DownloadOutlined,
} from '@ant-design/icons-vue';
import * as api from '@/api/settle/pre';

export default defineComponent({
  name: 'SettlePreSheet',
  components: {
    // Detail,
    ApproveRefuse,
  },
  setup() {
    return {
      h,
      SearchOutlined,
      PlusOutlined,
      CheckOutlined,
      CloseOutlined,
      DeleteOutlined,
      DownloadOutlined,
    };
  },
  data() {
    return {
      selectedKeys: ['required'], // 默认选中"所需物料"
      loading: false,
      // 当前行数据
      id: '',
      // 查询列表的查询条件
      searchFormData: {
        code: '',
        supplierId: '',
        createBy: '',
        createStartTime: this.$utils.formatDateTime(
          this.$utils.getDateTimeWithMinTime(moment().subtract(1, 'M')),
        ),
        createEndTime: this.$utils.formatDateTime(this.$utils.getDateTimeWithMaxTime(moment())),
        approveBy: '',
        approveStartTime: '',
        approveEndTime: '',
        status: undefined,
      },
      // 工具栏配置
      toolbarConfig: {
        // 自定义左侧工具栏
        slots: {
          buttons: 'toolbar_buttons',
        },
      },
      // 所需物料的列配置
      requiredMaterialColumns: [
        { type: 'checkbox', width: 45 },
        { field: 'code', title: '单据号', width: 180, sortable: true },
        { field: 'supplierCode', title: '供应商编号', width: 100 },
        { field: 'supplierName', title: '供应商名称', width: 120 },
        { field: 'totalAmount', title: '单据总金额', align: 'right', width: 100 },
        { field: 'createTime', title: '操作时间', width: 170, sortable: true },
        { field: 'createBy', title: '操作人', width: 100 },
        {
          field: 'status',
          title: '状态',
          width: 100,
          formatter: ({ cellValue }) => {
            return this.$enums.SETTLE_PRE_SHEET_STATUS.getDesc(cellValue);
          },
        },
        { field: 'approveTime', title: '审核时间', width: 170, sortable: true },
        { field: 'approveBy', title: '审核人', width: 100 },
        {
          field: 'settleStatus',
          title: '结算状态',
          width: 100,
          formatter: ({ cellValue }) => {
            return this.$enums.SETTLE_STATUS.getDesc(cellValue);
          },
        },
        { field: 'description', title: '备注', width: 200 },
        { title: '操作', width: 200, fixed: 'right', slots: { default: 'action_default' } },
      ],

      // 生产物料的列配置
      productionMaterialColumns: [
        { type: 'checkbox', width: 45 },
        { field: 'productCode', title: '产品编号', width: 180, sortable: true },
        { field: 'productName', title: '产品名称', width: 120 },
        { field: 'specification', title: '规格型号', width: 100 },
        { field: 'unit', title: '单位', width: 80 },
        { field: 'quantity', title: '数量', width: 100, align: 'right' },
        // ... 其他生产物料相关的列
      ],
      // 请求接口配置
      proxyConfig: {
        props: {
          // 响应结果列表字段
          result: 'datas',
          // 响应结果总条数字段
          total: 'totalCount',
        },
        ajax: {
          // 查询接口
          query: ({ page, sorts }) => {
            return api.query(this.buildQueryParams(page, sorts));
          },
        },
      },
    };
  },
  computed: {
    // 根据选中的菜单动态返回表格列配置
    tableColumn() {
      return this.selectedKeys[0] === 'required'
        ? this.requiredMaterialColumns
        : this.productionMaterialColumns;
    },
  },
  watch: {
    // 监听菜单选择变化
    selectedKeys: {
      handler(newVal) {
        // 切换表格数据
        this.loadTableData(newVal[0]);
      },
      immediate: true,
    },
  },
  created() {},
  methods: {
    // 列表发生查询时的事件
    search() {
      this.loadTableData(this.selectedKeys[0]);
    },
    // 查询前构建查询参数结构
    buildQueryParams(page, sorts) {
      return {
        //...this.$utils.buildSortPageVo(page, sorts),
        ...this.buildSearchFormData(),
      };
    },
    // 查询前构建具体的查询参数
    buildSearchFormData() {
      return {
        code: this.searchFormData.code,
        supplierId: this.searchFormData.supplierId,
        createBy: this.searchFormData.createBy,
        createStartTime: this.searchFormData.createStartTime,
        createEndTime: this.searchFormData.createEndTime,
        approveBy: this.searchFormData.approveBy,
        approveStartTime: this.searchFormData.approveStartTime,
        approveEndTime: this.searchFormData.approveEndTime,
        status: this.searchFormData.status,
        settleStatus: this.searchFormData.settleStatus,
      };
    },
    // 删除订单
    deleteOrder(row) {
      this.$msg.createConfirm('对选中的预付款单执行删除操作？').then(() => {
        this.loading = true;
        api
          .deleteById(row.id)
          .then(() => {
            this.$msg.createSuccess('删除成功！');
            this.search();
          })
          .finally(() => {
            this.loading = false;
          });
      });
    },
    // 批量删除
    batchDelete() {
      const records = this.$refs.grid.getCheckboxRecords();
      if (this.$utils.isEmpty(records)) {
        this.$msg.createError('请选择要执行操作的预付款单！');
        return;
      }

      for (let i = 0; i < records.length; i++) {
        if (this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_PASS.equalsCode(records[i].status)) {
          this.$msg.createError('第' + (i + 1) + '个预付款单已审核通过，不允许执行删除操作！');
          return;
        }
      }

      this.$msg.createConfirm('对选中的预付款单执行批量删除操作？').then((valid) => {
        if (valid) {
          this.loading = true;
          api
            .deleteByIds(records.map((item) => item.id))
            .then(() => {
              this.$msg.createSuccess('删除成功！');
              this.search();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    // 批量审核通过
    batchApprovePass() {
      const records = this.$refs.grid.getCheckboxRecords();
      if (this.$utils.isEmpty(records)) {
        this.$msg.createError('请选择要执行操作的预付款单！');
        return;
      }

      for (let i = 0; i < records.length; i++) {
        if (this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_PASS.equalsCode(records[i].status)) {
          this.$msg.createError('第' + (i + 1) + '个预付款单已审核通过，不允许继续执行审核！');
          return;
        }
      }

      this.$msg.createConfirm('对选中的预付款单执行审核通过操作？').then((valid) => {
        if (valid) {
          this.loading = true;
          api
            .batchApprovePass({
              ids: records.map((item) => item.id),
            })
            .then(() => {
              this.$msg.createSuccess('审核通过！');
              this.search();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    // 批量审核拒绝
    batchApproveRefuse() {
      const records = this.$refs.grid.getCheckboxRecords();
      if (this.$utils.isEmpty(records)) {
        this.$msg.createError('请选择要执行操作的预付款单！');
        return;
      }

      for (let i = 0; i < records.length; i++) {
        if (this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_PASS.equalsCode(records[i].status)) {
          this.$msg.createError('第' + (i + 1) + '个预付款单已审核通过，不允许继续执行审核！');
          return;
        }

        if (this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_REFUSE.equalsCode(records[i].status)) {
          this.$msg.createError('第' + (i + 1) + '个预付款单已审核拒绝，不允许继续执行审核！');
          return;
        }
      }

      this.$refs.approveRefuseDialog.openDialog();
    },
    doApproveRefuse(reason) {
      const records = this.$refs.grid.getCheckboxRecords();

      this.loading = true;
      api
        .batchApproveRefuse({
          ids: records.map((item) => item.id),
          refuseReason: reason,
        })
        .then(() => {
          this.$msg.createSuccess('审核拒绝！');
          this.search();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    exportList() {
      this.loading = true;
      api
        .exportList(this.buildQueryParams({}))
        .then(() => {
          this.$msg.createSuccessTip('导出成功！');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    createActions(row) {
      return [
        {
          label: '查看',
          onClick: () => {
            this.id = row.id;
            this.$nextTick(() => this.$refs.viewDialog.openDialog());
          },
        },
        {
          permission: ['settle:pre-sheet:approve'],
          label: '审核',
          ifShow: () => {
            return (
              this.$enums.SETTLE_PRE_SHEET_STATUS.CREATED.equalsCode(row.status) ||
              this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_REFUSE.equalsCode(row.status)
            );
          },
          onClick: () => {
            this.$router.push('/settle/supplier/pre-sheet/approve/' + row.id);
          },
        },
        {
          permission: ['settle:pre-sheet:modify'],
          label: '修改',
          ifShow: () => {
            return (
              this.$enums.SETTLE_PRE_SHEET_STATUS.CREATED.equalsCode(row.status) ||
              this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_REFUSE.equalsCode(row.status)
            );
          },
          onClick: () => {
            this.$router.push('/settle/supplier/pre-sheet/modify/' + row.id);
          },
        },
        {
          permission: ['settle:pre-sheet:delete'],
          label: '删除',
          color: 'error',
          ifShow: () => {
            return (
              this.$enums.SETTLE_PRE_SHEET_STATUS.CREATED.equalsCode(row.status) ||
              this.$enums.SETTLE_PRE_SHEET_STATUS.APPROVE_REFUSE.equalsCode(row.status)
            );
          },
          onClick: () => {
            this.deleteOrder(row);
          },
        },
      ];
    },
    // 加载表格数据
    loadTableData(type) {
      this.loading = true;
      console.log(type);
      setTimeout(() => {
        this.loading = false;
      }, 1000);
      // 根据不同类型调用不同的接口
      // const api = type === 'required' ? this.queryRequiredMaterials : this.queryProductionMaterials;

      // api()
      //   .then((res) => {
      //     // 处理数据
      //     this.tableData = res.data;
      //   })
      //   .finally(() => {
      //     this.loading = false;
      //   });
    },

    // 查询所需物料数据
    queryRequiredMaterials() {
      // 调用所需物料相关的API
      //return api.query(this.buildQueryParams());
    },

    // 查询生产物料数据
    queryProductionMaterials() {
      // 调用生产物料相关的API
      //return api.queryProduction(this.buildQueryParams());
    },
  },
});
</script>
<style scoped lang="less">
/deep/ .j-form-item {
  width: 25% !important;

  .ant-input-affix-wrapper {
    align-items: center;
  }
  &.timeData {
    .j-form-item-content {
      width: 60% !important;
      .ant-space {
        width: 100% !important;
        gap: 0px !important;
        .ant-space-item {
          width: 100% !important;
          .ant-picker {
            width: 100% !important;
            box-sizing: border-box;
          }
        }
      }
    }
  }
  .full-width {
    // width:60% !important;
  }
}

.custom-menu {
  margin: 0;
  background: #fff;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.ant-menu-horizontal) {
  border-bottom: none;
  line-height: 40px;
}

.product-search-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
  width: 25% !important;
  margin-right: 16px;

  .full-width {
    width: 100% !important;
    margin-bottom: 0;
  }

  .search-btn {
    align-self: flex-start;
    margin-left: 112px; // 与表单项对齐，根据实际label宽度调整
  }
}

// 移除工具栏中的查询按钮
:deep(.toolbar_buttons) {
  .ant-btn-primary:first-child {
    display: none;
  }
}
</style>
